package xendit

import (
	"encoding/json"
	"errors"
	"time"

	"gitee.com/gxcc/go-utils/utils"
)

type OvoRequest struct {
	ExternalId  string `json:"external_id"`
	Amount      int64  `json:"amount"`
	Phone       string `json:"phone"`
	EwalletType string `json:"ewallet_type"`
}

type OvoResponse struct {
	Id              int64      `json:"id" gorm:"primary_key;auto_increment"`
	TransactionDate *time.Time `json:"transaction_date"`
	ExternalId      string     `json:"external_id"`
	Amount          int64      `json:"amount"`
	Phone           string     `json:"phone"`
	EwalletType     string     `json:"ewallet_type"`
	BussinessId     string     `json:"bussiness_id"`
	Status          string     `json:"status"`
}

func (OvoResponse) TableName() string {
	return "xen_ovo_response"
}

// 创建ovo支付请求，ovo支付结果会直接返回,没有错误提示即支付成功
func (svc *XenditSvc) CreateEwalletOvo(externalId string, amount int64, phone string) (OvoResponse, error) {
	var params = OvoRequest{
		ExternalId:  externalId,
		Amount:      amount,
		Phone:       phone,
		EwalletType: "OVO",
	}
	url := "https://api.xendit.co/ewallets"
	headers := map[string]string{
		"Content-Type":  "application/json",
		"Authorization": svc.ApiKey,
	}

	req, err := json.Marshal(params)
	if err != nil {
		return OvoResponse{}, errors.New("create ovo pay request failed")
	}

	res, err := utils.HttpPost(url, headers, req)
	if err != nil {
		return OvoResponse{}, errors.New("create ovo pay request failed")
	}
	resMap := make(map[string]string)
	json.Unmarshal(res.Body, &resMap)
	if len(resMap["error_code"]) > 0 {
		return OvoResponse{}, errors.New(resMap["error_code"])
	}
	var ovoResponse OvoResponse
	json.Unmarshal(res.Body, &ovoResponse)

	return ovoResponse, nil
}

// 查询支付结果
func (svc *XenditSvc) GetEwalletPaymentStatus(externalId string, ewalletType string) (OvoResponse, error) {
	url := "https://api.xendit.co/ewallets?external_id=" + externalId + "&ewallet_type=" + ewalletType
	headers := map[string]string{
		"Content-Type":  "application/json",
		"Authorization": svc.ApiKey,
	}

	res, err := utils.HttpGet(url, headers)
	if err != nil {
		return OvoResponse{}, errors.New("get ovo payment status failed")
	}
	resMap := make(map[string]string)
	json.Unmarshal(res.Body, &resMap)
	if len(resMap["error_code"]) > 0 {
		return OvoResponse{}, errors.New(resMap["error_code"])
	}

	var ovoResponse OvoResponse
	json.Unmarshal(res.Body, &ovoResponse)
	if ovoResponse.Status != "COMPLETED" {
		return OvoResponse{}, errors.New("ovo payment not completed")
	}

	return ovoResponse, nil
}
